<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from "@/utils/request"
import { useUserStore } from '@/stores/modules/user'

const router = useRouter()
const userStore = useUserStore()

//近期计划数据
const recentPlans = ref([])
const loading = ref(false)

//对话框状态
const addDialogVisible = ref(false)
const addFormRef = ref()

//新计划数据
const newPlan = ref({
    name: '',
    date: '',
    type: 'single',
    startTime: '',
    endTime: '',
    content: '',
    cycleNumber: 1,
    cycleUnit: 'days'
})

//表单验证规则
const formRules = {
    name: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
    date: [{ required: true, message: '请选择日期', trigger: 'change' }],
    type: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (newPlan.value.startTime && value < newPlan.value.startTime) {
                    callback(new Error('结束时间不能早于开始时间'))
                } else {
                    callback()
                }
            },
            trigger: 'change'
        }
    ],
    content: [{ required: true, message: '请输入计划内容', trigger: 'blur' }],
    cycleNumber: [
        {
            required: true,
            message: '请输入周期数值',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (newPlan.value.type === 'periodic' && !value) {
                    callback(new Error('周期数值不能为空'))
                } else {
                    callback()
                }
            }
        }
    ]
}

// 获取学生ID
const getStuId = () => {
    try {
        const rawInfo = localStorage.getItem('studentUserInfo')
        if (!rawInfo) {
            console.error('无登录信息')
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return null
        }

        const userInfo = JSON.parse(rawInfo)
        if (!userInfo?.stu_id) {
            localStorage.removeItem('studentUserInfo')
            console.error('登录信息无效')
            ElMessage.warning('登录信息无效，请重新登录')
            router.push('/student/login')
            return null
        }
        return userInfo.stu_id
    } catch (e) {
        console.error('学生ID获取失败:', e)
        ElMessage.error('登录信息解析失败')
        router.push('/student/login')
        return null
    }
}

// 获取用户名
const getUsername = () => {
    try {
        const rawInfo = localStorage.getItem('studentUserInfo')
        if (!rawInfo) return null

        const userInfo = JSON.parse(rawInfo)
        return userInfo?.username || null
    } catch (e) {
        return null
    }
}

//从API加载计划数据
const loadPlans = async () => {
    try {
        loading.value = true
        console.log('开始加载近期计划数据...')

        const userId = getStuId()
        const username = getUsername()

        if (!userId && !username) {
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return
        }

        const params = {
            days: 3,  // 获取近3天的计划
            use_sql: true
        }

        // 优先使用用户名，其次使用学生ID
        if (username) {
            params.username = username
        } else if (userId) {
            params.stu_id = userId
        }

        // 添加调试信息
        console.log('请求参数:', params)

        try {
            const response = await request.get('/api/student/study-plan/', {
                params,
                timeout: 8000
            })

            console.log('计划数据响应状态:', response.status)
            console.log('计划数据响应类型:', typeof response.data)

            // 确定数据来源
            let planData = null

            // 直接从响应中获取数据
            if (response.data !== undefined) {
                console.log('直接从response.data获取数据')
                planData = response.data
            } else if (response.data?.data !== undefined) {
                console.log('从response.data.data获取数据')
                planData = response.data.data
            }

            // 如果planData是字符串，尝试解析为JSON
            if (typeof planData === 'string') {
                try {
                    console.log('尝试解析字符串类型的数据为JSON')
                    planData = JSON.parse(planData)
                    console.log('解析成功，解析后类型:', typeof planData)
                } catch (parseError) {
                    console.error('JSON解析失败:', parseError)
                }
            }

            // 检查获取到的数据
            console.log('获取到的数据类型:', typeof planData)
            console.log('数据是否为数组:', Array.isArray(planData))

            if (Array.isArray(planData)) {
                console.log('数组长度:', planData.length)
                if (planData.length > 0) {
                    console.log('第一条数据示例:', planData[0])
                }
            }

            // 处理数据类型为object的情况
            if (typeof planData === 'object' && planData !== null && !Array.isArray(planData)) {
                console.log('planData是对象类型，尝试从对象中提取数组数据')

                // 尝试所有可能的数组字段
                const possibleArrayFields = ['plans', 'data', 'items', 'list', 'results']

                for (const field of possibleArrayFields) {
                    if (Array.isArray(planData[field])) {
                        console.log(`找到数组字段: ${field}, 长度: ${planData[field].length}`)
                        planData = planData[field]
                        break
                    }
                }

                // 如果对象有任何数组类型的属性，使用第一个找到的
                if (!Array.isArray(planData)) {
                    for (const key in planData) {
                        if (Array.isArray(planData[key]) && planData[key].length > 0) {
                            console.log(`使用对象的数组属性: ${key}, 长度: ${planData[key].length}`)
                            planData = planData[key]
                            break
                        }
                    }
                }

                // 如果对象包含单个计划数据，将其包装为数组
                if (!Array.isArray(planData) && typeof planData === 'object' &&
                    (planData.plan_id || planData.id || planData.plan_name)) {
                    console.log('对象似乎是单个计划数据，包装为数组')
                    planData = [planData]
                }
            }

            if (Array.isArray(planData) && planData.length > 0) {
                // 数据存在且有效
                recentPlans.value = planData.map(plan => {
                    // 确保每个计划都有必要的字段
                    const normalizedPlan = {
                        // 使用id作为主键（尝试各种可能的ID字段）
                        id: plan.id || plan.plan_id || plan.planId || plan.pid || plan._id,

                        // 标准化名称字段
                        plan_name: plan.plan_name || plan.name || plan.title || plan.planName,

                        // 标准化日期字段
                        plan_date: plan.plan_date || plan.date || plan.planDate ||
                                  (typeof plan.time === 'object' ? plan.time.date : null),

                        // 标准化类型字段
                        plan_type: plan.plan_type || plan.type || plan.planType || 'single',

                        // 标准化时间字段
                        start_time: plan.start_time || plan.startTime || plan.start ||
                                   (typeof plan.time === 'object' ? plan.time.start : null),
                        end_time: plan.end_time || plan.endTime || plan.end ||
                                 (typeof plan.time === 'object' ? plan.time.end : null),

                        // 标准化内容字段
                        plan_content: plan.plan_content || plan.content || plan.description || plan.desc,

                        // 标准化周期字段
                        cycle_value: plan.cycle_value || plan.cycleValue ||
                                    (typeof plan.cycle === 'object' ? plan.cycle.value : null),
                        cycle_unit: plan.cycle_unit || plan.cycleUnit ||
                                   (typeof plan.cycle === 'object' ? plan.cycle.unit : null),
                    }

                    // 添加周期显示
                    if (normalizedPlan.plan_type === 'periodic' && normalizedPlan.cycle_value && normalizedPlan.cycle_unit) {
                        normalizedPlan.cycle = `${normalizedPlan.cycle_value} ${normalizedPlan.cycle_unit}`
                    } else if (plan.cycle && typeof plan.cycle === 'string') {
                        normalizedPlan.cycle = plan.cycle
                    }

                    // 处理不同格式的日期
                    normalizedPlan.plan_date = formatDateForDisplay(normalizedPlan.plan_date)

                    console.log('标准化后的计划数据:', normalizedPlan)
                    return normalizedPlan
                })
                console.log('成功加载计划数据，条数:', recentPlans.value.length)
            } else {
                console.warn('返回的计划数据为空或格式不正确:', planData)
                // 使用默认数据
                recentPlans.value = getDefaultPlans()
                console.log('使用默认计划数据')
            }
        } catch (apiError) {
            console.error('API请求失败:', apiError)
            // 使用默认数据
            recentPlans.value = getDefaultPlans()
            console.log('请求失败，使用默认计划数据')
        }
    } catch (error) {
        console.error('获取计划数据总体失败:', error)
        ElMessage.error('加载计划数据失败')
        // 出错时也使用默认数据
        recentPlans.value = getDefaultPlans()
    } finally {
        loading.value = false
    }
}

// 获取默认的计划数据
const getDefaultPlans = () => {
    return [
        {
            id: 1,
            plan_id: 1,
            plan_name: '数据结构复习',
            plan_date: '2025-05-20',
            plan_type: 'single',
            start_time: '08:30',
            end_time: '10:30',
            plan_content: '复习二叉树和图论相关知识点，完成课后习题1-5'
        },
        {
            id: 2,
            plan_id: 2,
            plan_name: '算法设计作业',
            plan_date: '2025-05-20',
            plan_type: 'single',
            start_time: '14:00',
            end_time: '16:00',
            plan_content: '完成动态规划算法设计作业，提交到教学平台'
        },
        {
            id: 3,
            plan_id: 3,
            plan_name: '英语四级单词',
            plan_date: '2025-05-20',
            plan_type: 'single',
            start_time: '19:30',
            end_time: '20:30',
            plan_content: '背诵Unit 5的核心词汇，复习上周学过的单词'
        },
        {
            id: 4,
            plan_id: 4,
            plan_name: '晨跑锻炼',
            plan_date: '2025-05-21',
            plan_type: 'periodic',
            start_time: '06:30',
            end_time: '07:15',
            plan_content: '晨跑30分钟，保持身体健康和良好的精神状态',
            cycle_value: 1,
            cycle_unit: 'days'
        }
    ]
}

//格式化时间显示
const formatTime = (time) => {
    if (!time) return ''
    const [hours, minutes] = time.split(':')
    return `${hours.padStart(2, '0')}:${minutes.padStart(2, '0')}`
}

//格式化日期显示
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    })
}

// 格式化日期确保统一格式
const formatDateForDisplay = (dateValue) => {
    if (!dateValue) return ''

    try {
        // 如果是ISO格式日期字符串
        if (typeof dateValue === 'string') {
            // 只提取日期部分 (YYYY-MM-DD)
            if (dateValue.includes('T')) {
                return dateValue.split('T')[0]
            }
            return dateValue
        }

        // 如果是Date对象
        if (dateValue instanceof Date) {
            return dateValue.toISOString().split('T')[0]
        }

        // 其他情况，尝试转为字符串
        return String(dateValue)
    } catch (e) {
        console.error('日期格式化错误:', e)
        return dateValue // 返回原始值
    }
}

//显示添加对话框
const showAddDialog = () => {
    addDialogVisible.value = true
    newPlan.value = {
        name: '',
        date: '',
        type: 'single',
        startTime: '',
        endTime: '',
        content: '',
        cycleNumber: 1,
        cycleUnit: 'days'
    }
}

//提交新计划
const submitNewPlan = async () => {
    try {
        await addFormRef.value.validate()

        const userId = getStuId()
        const username = getUsername()

        if (!userId && !username) {
            ElMessage.warning('请先登录')
            router.push('/student/login')
            return
        }

        // 准备提交的数据 - 将前端字段名映射到后端字段名
        const planData = {
            plan_name: newPlan.value.name,
            plan_date: newPlan.value.date,
            plan_type: newPlan.value.type,
            start_time: newPlan.value.startTime,
            end_time: newPlan.value.endTime,
            plan_content: newPlan.value.content,
            cycle_value: newPlan.value.type === 'periodic' ? newPlan.value.cycleNumber : null,
            cycle_unit: newPlan.value.type === 'periodic' ? newPlan.value.cycleUnit : null
        }

        // 添加用户标识
        if (username) {
            planData.username = username
        }
        if (userId) {
            planData.stu_id = userId
        }

        console.log('提交计划数据:', planData)

        // 发送API请求
        const response = await request.post('/api/student/study-plan/', planData)

        console.log('添加计划响应:', response)

        // 根据API响应进行处理
        if (response.status === 201 || response.status === 200) {
        ElMessage.success('计划添加成功')
        addDialogVisible.value = false
            // 重新加载计划数据
            await loadPlans()
        } else {
            ElMessage.error(response.data?.error || '添加计划失败')
        }
    } catch (error) {
        console.error('添加计划失败:', error)
        ElMessage.error('添加计划失败，请检查输入')
    }
}

//查看详情（示例）
const viewPlanDetails = (plan) => {
    // 可以在这里实现跳转到详情页面
    console.log('查看计划详情:', plan)
}

//跳转到计划页面
const toPersonalPlan = () => {
    router.push('/student/plan/PersonalPlan')
}

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

//初始化加载数据
onMounted(() => {
    loadPlans()
})
</script>

<template>
<div class="study-plan-container">
    <div class="recent-plans-page">
        <div class="header">
            <h2>近期计划</h2>
            <el-button type="primary" @click="showAddDialog">添加计划</el-button>
        </div>

        <el-scrollbar class="plan-scroll">
                <div v-if="loading" class="loading-container">
                    <el-skeleton :rows="3" animated />
                </div>
                <div v-else-if="recentPlans.length === 0" class="empty-container">
                    <el-empty description="暂无近期计划" />
                </div>
                <div v-else class="plan-list">
                <el-card
                    v-for="plan in recentPlans"
                    :key="plan.id"
                    class="plan-card"
                    @click="viewPlanDetails(plan)"
                >
                    <div class="card-content">
                            <h3>{{ plan.plan_name }}</h3>
                        <div class="time-info">
                                <span class="date">{{ formatDate(plan.plan_date) }}</span>
                                <span class="time">{{ formatTime(plan.start_time) }} - {{ formatTime(plan.end_time) }}</span>
                            </div>
                            <el-tag v-if="plan.plan_type === 'periodic'" type="warning">周期计划</el-tag>
                            <div class="plan-content">
                                {{ plan.plan_content }}
                                <div v-if="plan.plan_type === 'periodic'" class="cycle-info">
                                    <span>周期：{{ plan.cycle || `${plan.cycle_value} ${plan.cycle_unit}` }}</span>
                                </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </el-scrollbar>

        <div class="footer">
            <el-button
                type="primary"
                @click="toPersonalPlan"
            >查看完整计划表</el-button>
        </div>

        <el-dialog
            v-model="addDialogVisible"
            title="添加新计划"
            width="600px"
        >
            <el-form
                :model="newPlan"
                label-width="80px"
                :rules="formRules"
                ref="addFormRef"
            >
                <el-form-item label="计划名称" prop="name">
                    <el-input v-model="newPlan.name" />
                </el-form-item>

                <el-form-item label="计划日期" prop="date">
                    <el-date-picker
                        v-model="newPlan.date"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>

                <el-form-item label="计划类型" prop="type">
                    <el-select v-model="newPlan.type">
                        <el-option label="单次计划" value="single" />
                        <el-option label="周期计划" value="periodic" />
                    </el-select>
                </el-form-item>

                <el-form-item label="开始时间" prop="startTime">
                    <el-time-picker
                        v-model="newPlan.startTime"
                        format="HH:mm"
                        value-format="HH:mm"
                    />
                </el-form-item>

                <el-form-item label="结束时间" prop="endTime">
                    <el-time-picker
                        v-model="newPlan.endTime"
                        format="HH:mm"
                        value-format="HH:mm"
                    />
                </el-form-item>

                <template v-if="newPlan.type === 'periodic'">
                    <el-form-item label="周期设置" prop="cycle">
                        <div class="cycle-input-group">
                            <el-input-number
                                v-model="newPlan.cycleNumber"
                                :min="1"
                                :max="30"
                                controls-position="right"
                            />
                            <el-select v-model="newPlan.cycleUnit">
                                <el-option label="小时" value="hours" />
                                <el-option label="天" value="days" />
                                <el-option label="周" value="weeks" />
                                <el-option label="月" value="months" />
                            </el-select>
                        </div>
                    </el-form-item>
                </template>

                <el-form-item label="计划内容" prop="content">
                    <el-input
                        v-model="newPlan.content"
                        type="textarea"
                        :rows="4"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitNewPlan">确认添加</el-button>
            </template>
        </el-dialog>
        </div>

<!--    <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/Ql1E9ZJwmiDKRNTM" class="chat-iframe"></iframe>-->
<!--    </div>-->
    </div>
</template>
<style scoped>
.study-plan-container {
    padding: 20px;
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.recent-plans-page {
    padding: 20px;
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.plan-scroll {
    flex: 1;
    margin-bottom: 20px;
}

.loading-container,
.empty-container {
    padding: 40px 20px;
    text-align: center;
}

.plan-list {
    display: flex;
    gap: 15px;
    padding: 10px 0;
}

.plan-card {
    width: 280px;
    flex-shrink: 0;
    cursor: pointer;
    transition: transform 0.2s;
}

.plan-card:hover {
    transform: translateY(-3px);
}

.card-content {
    padding: 10px;
}

.time-info {
    margin: 10px 0;
    display: flex;
    flex-direction: column;
    gap: 5px;
    color: #666;
}

.date {
    font-size: 14px;
}

.time {
    font-size: 16px;
    font-weight: 500;
    color: #409eff;
}

.plan-content {
    margin-top: 10px;
    font-size: 14px;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

.cycle-input-group {
    display: flex;
    gap: 10px;
}

.cycle-info {
    margin-top: 10px;
    font-size: 12px;
    color: #666;
    padding: 4px 0;
    border-top: 1px dashed #eee;
}

.cycle-info span {
    display: inline-block;
    color: #e6a23c;
    font-weight: 500;
}

.footer {
    text-align: center;
    padding: 20px 0;
    border-top: 1px solid #ebeef5;
}

#dify-chatbot-bubble-button {
    background-color: #1C64F2 !important;
  }
  #dify-chatbot-bubble-window {
    width: 24rem !important;
    height: 40rem !important;
}
.chat-bubble {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            background-color: #007bff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
        }

        .chat-bubble img {
            width: 30px;
            height: 30px;
        }

        .chat-container {
            position: fixed;
            bottom: 100px;
            right: 20px;
            width: 350px;
            height: 500px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            display: none;
            z-index: 999;
        }

        .chat-iframe {
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 10px;
}
</style>
